package com.test.template.publish.config.fac;

import com.elecbook.content.model.po.Contribute;
import com.test.template.publish.config.XmlSubmitConfig;
import com.test.template.publish.config.manager.VelocityConfigManager;
import com.test.template.publish.invoke.InvokeUtil;
import com.test.template.publish.invoke.PropComment;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class XmlSubmitConfigFactory implements VelocityTemplateConfigFactory<XmlSubmitConfig> {

    ConcurrentHashMap<String, XmlSubmitConfig> configHashMap = new ConcurrentHashMap<>();

    // **单例定义
    // 私有静态变量保存唯一实例
    private static volatile XmlSubmitConfigFactory instance = null;

    // **单例定义
    // 公共静态方法提供全局访问点
    public static XmlSubmitConfigFactory getInstance() {
        if (instance == null) {
            synchronized (XmlSubmitConfigFactory.class) {
                if (instance == null) {
                    instance = new XmlSubmitConfigFactory();
                    init();
                }
            }
        }
        return instance;
    }

    /**
     * description 初始化函数，后续修改为配置文件读取方式执行
     *
     * @author zken
     * @CreateDate 2024/12/6 20:46:59
     */
    private static void init() {
        XmlSubmitConfig contributeConfig = buildBasicConfig("contribute",
                Contribute.class,
                "@/model/",
                "@/api/content/contribute/contribute.js");
        getInstance().addConfig("contribute", contributeConfig);
    }

    /**
     * 创建
     *
     * @param tableName
     * @param clazz
     * @param entityPath
     * @param apiPath
     * @return
     */
    public static XmlSubmitConfig buildBasicConfig(String tableName, Class<?> clazz,
                                                   String entityPath, String apiPath) {
        XmlSubmitConfig xmlConfig = new XmlSubmitConfig();
        xmlConfig.setTableName(tableName);
        List<PropComment> props = InvokeUtil.getPropComments(clazz);
        xmlConfig.setProps(props);
        xmlConfig.setEntityPath(entityPath);
        xmlConfig.setApiPath(apiPath);
        xmlConfig.innerGenerate();
        return xmlConfig;
    }


    // 私有构造函数防止实例化
    private XmlSubmitConfigFactory() {

    }

    @Override
    public void addConfig(String key, XmlSubmitConfig config) {
        configHashMap.put(key, config);
    }

    @Override
    public XmlSubmitConfig getConfig(String key) {
        return configHashMap.get(key);
    }

    @Override
    public void addConfig(VelocityConfigManager manager) {
        XmlSubmitConfig config = buildBasicConfig(manager.getTableName(), manager.getClazzPo(), manager.getJsEntityPath(), manager.getJsApiPath());
        getInstance().addConfig(manager.getTableName(), config);
    }
}
